package test5.lupeng.jf.com.teamdemo.fragment;


import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.MainActivity;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.untils.Appconfig;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;
import test5.lupeng.jf.com.teamdemo.untils.StringUtils;

import static android.content.ContentValues.TAG;
/**
 * 注册界面
 */
public class LoginFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
          initView(view);
    }

    /**
     * 初始化
     * @param view
     */
    private void initView(View view) {
        final EditText ed_loginName = view.findViewById(R.id.ed_loginName);
        final EditText ed_loginPassword = view.findViewById(R.id.ed_loginPassword);
         Button bt_login= view.findViewById(R.id.bt_login);
          TextView tv_regist= view.findViewById(R.id.tv_regist);
        //登录按钮的点击事件
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username =  ed_loginName.getText().toString();
                String password = ed_loginPassword.getText().toString();
              boolean nameIsCorrect=  StringUtils.checkUserName(username,ed_loginName);
              boolean passwordIsCorretct=  StringUtils.checkPassword(password,ed_loginPassword);
                if(nameIsCorrect&&passwordIsCorretct){
                    login(username,password);
                }

            }
        });

        tv_regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RegistFragment registFragment  = new RegistFragment();
                FragmentTransaction transaction =getFragmentManager().beginTransaction();
                transaction.replace(R.id.fl,registFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });


    }


    /**
     * 登录帐号
     * @param username
     * @param password
     */
    private  void login(String username,String password){
        OkHttpClient client  = new OkHttpClient();
        String url = "https://leancloud.cn:443/1.1/login?username="+username+"&password="+password;
        Request request= HTTPUtils.requestGet(url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                Log.i(TAG, "onResponse: "+result);
                try {
                    JSONObject object = new JSONObject(result);
                    String userId=object.getString("objectId");
                    String userName=object.getString("username");
                    //设置登录状态
                    Appconfig.getInstance().setLoginStatus(true);

                    SharedPreferences.Editor editor=getActivity().getSharedPreferences("LoginStatus",getActivity().MODE_PRIVATE).edit();
                    editor.putBoolean("isLogin", true);
                    editor.commit();

                    //存储呢到本地
                    SharedPreferences.Editor et=getActivity().getSharedPreferences("config",getActivity().MODE_PRIVATE).edit();
                    et.putString("objectId", userId);
                    et.putString("userName", userName);
                    et.apply();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent=new Intent(getActivity(), MainActivity.class);

                startActivity(intent);
                getActivity().finish();



            }
        });



    }
}
